package org.tls.ylt.user.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.tls.ylt.common.helper.EmailHelper;
import org.tls.ylt.common.result.Result;
import org.tls.ylt.common.utils.AuthContextHolder;
import org.tls.ylt.common.utils.IpUtil;
import org.tls.ylt.model.user.UserInfo;
import org.tls.ylt.user.service.EmailService;
import org.tls.ylt.user.service.UserInfoService;
import org.tls.ylt.vo.user.LoginVo;
import org.tls.ylt.vo.user.UserAuthVo;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Api("用户管理")
@Controller
@ResponseBody
@RequestMapping("/api/user")
public class UserInfoApiController {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private EmailService emailService;

    @Autowired
    private UserInfoService userInfoService;

    @ApiOperation(value = "会员登录")
    @PostMapping("login")
    public Result login(@RequestBody LoginVo loginVo, HttpServletRequest request) {
        System.out.println(loginVo);
        loginVo.setIp(IpUtil.getIpAddr(request));
        Map<String, Object> info = userInfoService.login(loginVo);
        System.out.println(info.get("name"));
        return Result.ok(info);
    }

    //发送邮箱验证码
    @GetMapping("email/{email}")
    public Result sendCode(@PathVariable String email) {
        if(emailService.send(email)) return Result.ok("邮箱发送成功！");
        //return Result.fail("邮箱发送失败！");
        return Result.ok("邮箱发送失败！");
    }

    //用户认证接口
    @PostMapping("auth/userAuth")
    public Result userAuth(@RequestBody UserAuthVo userAuthVo, HttpServletRequest request) {
        //传递两个参数，第一个参数用户id，第二个参数认证数据vo对象
        //AuthContextHolder从token中取出id
        userInfoService.userAuth(AuthContextHolder.getUserId(request),userAuthVo);
        return Result.ok();
    }

    //获取用户id信息接口
    @GetMapping("auth/getUserInfo")
    public Result getUserInfo(HttpServletRequest request) {
        //根据token获取id，进而获取所有用户信息
        Long userId = AuthContextHolder.getUserId(request);
        UserInfo userInfo = userInfoService.getById(userId);
        return Result.ok(userInfo);
    }
}
